package com.good.shopping.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.good.common.constant.AuthServerConstant;
import com.good.common.constant.HostConstant;
import com.good.common.exception.BizCodeEnum;
import com.good.common.to.auth.MemberRespVo;
import com.good.common.utils.R;
import com.good.shopping.auth.fegin.MemberFeignService;
import com.good.shopping.auth.fegin.ThirdPartyFeignService;
import com.good.shopping.auth.vo.UserLoginVo;
import com.good.shopping.auth.vo.UserRegisterVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author yan
 */
@Controller
public class LoginController {

    // 第三方服务
    @Autowired
    private ThirdPartyFeignService feignService;

    // redis
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MemberFeignService memberFeignService;

    // 获取验证码
    //    短信  -验证码 保存到 redis中
    //          格式 ： sms:code:18510808418  里面是 code_创建的时间
    //                  例子： sms:code:18510808411  值：764087_1646721033890
    //                         sms:code:18510808412  值：224087_1646721033890
    @GetMapping("/sms/sendCode")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone){
        //1、接口防刷
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (StringUtils.isNotBlank(redisCode)) {
            //redis存的时间戳
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 60000) {
                //1分钟内已给这个手机号发过短信，不能在发
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        //2、验证码再次校验，存redis ,key=phone,value=code
        // String code = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 5);
        int num = (int) ((Math.random() * 9 + 1) * 100000);
        String code = String.valueOf(num);

        //redis中存储的验证码+时间戳
        String redisValue = code + "_" + System.currentTimeMillis();
        //redis缓存验证码，防止同一个手机号再次发送验证码
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, redisValue, 10, TimeUnit.MINUTES);
        // 发送短信接口
        feignService.sendCode(phone, code);
        return R.ok();
    }

    /**
     * 注册
     *      BindingResult  JSP303验证返回对象
     *
     * @param vo
     * @param result 利用session原理，将数据放在session中，只要跳到下一个页面的取出这个数据以后，session里面的数据就会被删掉
     * @param redirectAttributes: 模拟重定向携带数据
     * @return
     */
    @PostMapping("/register")
    public String register(@Valid UserRegisterVo vo, BindingResult result, RedirectAttributes redirectAttributes){
        if (result.hasErrors()){
            //校验出错，转发到注册页
            Map<String, String> map = result.getFieldErrors().stream()
                    .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors",map);
            return "redirect:" + HostConstant.AUTH_HOST + "/reg.html";
        }
        //真正注册，调用远程服务注册
        //1、校验验证码
        String code = vo.getCode();
        // 从缓存中拿到验证码
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (StringUtils.isNotBlank(s)) {
            if (code.equals(s.split("_")[0])) {
                //删除验证码
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                //验证码校验通过,真正注册，调用远程服务注册
                R r = memberFeignService.regist(vo);
                if (r.getCode() == 0) {
                    //成功,转到登录页
                    return "redirect:" + HostConstant.AUTH_HOST + "/login.html";
                } else {
                    Map<String, Object> map = new HashMap<>();
                    map.put("msg", r.get("msg"));
                    System.out.println(map);
                    redirectAttributes.addFlashAttribute("errors", map);
                    //return "redirect:" + HostConstant.AUTH_HOST + "/reg.html";
                }
            } else {
                Map<String, Object> map = new HashMap<>();
                map.put("code", "验证码输入错误");
                redirectAttributes.addFlashAttribute("errors", map);
                //校验出错，转发到注册页
                //return "redirect:" + HostConstant.AUTH_HOST + "/reg.html";
            }
        } else {
            Map<String, Object> map = new HashMap<>();
            map.put("code", "验证码输入错误");
            redirectAttributes.addFlashAttribute("errors", map);
            //校验出错，转发到注册页 - 带域名
            //return "redirect:" + HostConstant.AUTH_HOST + "/reg.html";
        }
        return "redirect:" + HostConstant.AUTH_HOST + "/reg.html";
    }


    // 登录
    // RedirectAttributes 因为前端是模板引擎开发，
    //      类似 Model model  model.addAttribute("result",result);
    //      由于有转发、重定向 需要使用 RedirectAttributes 进行给页面赋值  redirectAttributes.addFlashAttribute("errors", errors);
    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes,HttpSession session){
        //远程登录
        R r = memberFeignService.login(vo);
        if (r.getCode() == 0) {
            // 登录成功
            MemberRespVo data = r.getData(new TypeReference<MemberRespVo>() {});
            session.setAttribute(AuthServerConstant.SESSION_LOGIN_KEY,data);
            return "redirect:" + HostConstant.GHOST;
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", r.getData("msg", new TypeReference<String>() {}));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:" + HostConstant.AUTH_HOST + "/login.html";
        }
    }

    // 登录页
    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.SESSION_LOGIN_KEY);
        if (attribute == null){
            //没登录去登录页
            return "login";
        }else {
            //已登录去首页
            return "redirect:" + HostConstant.GHOST;
        }
    }

//    @GetMapping("/login2.html")
//    public String loginPage2(HttpSession session){
//        return "index";
//    }

}
